package easier.app.x.recycler;

import android.os.Handler;
import androidx.annotation.NonNull;
import androidx.viewpager2.widget.ViewPager2;
import java.util.List;

/**
 * 辅助{@link ViewPager2}创建轮播图,自动轮播,初始位置位于{@link Integer#MAX_VALUE}的一半,造成前后都有无线条数据的假象
 */
public class InfinitePager {

    private ViewPager2 mViewPager2;

    private final Handler mHandler = new Handler();
    private final Runnable mRunnable = new Runnable() {
        @Override
        public void run() {

            int scrollState = mViewPager2.getScrollState();
            if ( scrollState == ViewPager2.SCROLL_STATE_IDLE ) {
                if ( mViewPager2.getAdapter() != null ) {
                    int currentItem = mViewPager2.getCurrentItem();
                    int nextItem = currentItem + 1;
                    if ( nextItem < mViewPager2.getAdapter().getItemCount() ) {
                        mViewPager2.setCurrentItem( nextItem, true );
                    } else {
                        mViewPager2.setCurrentItem( nextItem / 2, false );
                    }
                }
            }

            mHandler.postDelayed( this, mDelayMillis );
        }
    };
    private int mDelayMillis;

    public InfinitePager() {

    }

    public InfinitePager( @NonNull ViewPager2 viewPager2, List< TypeViewHolder > holders ) {

        build( viewPager2, holders );
    }

    public void build( @NonNull ViewPager2 viewPager2, List< TypeViewHolder > holders ) {

        mViewPager2 = viewPager2;
        InfiniteAdapter adapter = new InfiniteAdapter( holders );
        mViewPager2.setAdapter( adapter );
        int currentItem = adapter.getItemCount() / 2;
        mViewPager2.setCurrentItem( currentItem - (currentItem % holders.size()), false );
    }

    public void update( List< TypeViewHolder > holders ) {

        if ( mViewPager2 == null ) {
            return;
        }

        if ( !(mViewPager2.getAdapter() instanceof InfiniteAdapter) ) {
            return;
        }

        ((InfiniteAdapter) mViewPager2.getAdapter()).updateViewHolders( holders );
    }

    public void start( int delayMillis ) {

        mDelayMillis = delayMillis;
        mHandler.removeCallbacks( mRunnable );
        mHandler.postDelayed( mRunnable, delayMillis );
    }

    public void stop() {

        mHandler.removeCallbacks( mRunnable );
    }
}
